/* main.c */
#include "app_inc.h"

void RCC_Configuration(void);
void GPIO_Configuration(void);
void SPI1_Configuration(void);
uint8_t SPI1_SwapBytePolling(uint8_t ch);

int main(void)
{
    char ch;

    BSP_InitStdioUART(115200U);
    RCC_Configuration();
    GPIO_Configuration();
    SPI1_Configuration();

    printf("SPI_XferSelfLoop Example ...\r\n");

    while (1)
    {
        printf("\r\n");
        ch = getchar();
        printf("SPI Tx Token: %c\r\n", ch);
        ch = SPI1_SwapBytePolling(ch);
        printf("SPI Rx Token: %c\r\n", ch);
    }
}

void RCC_Configuration(void)
{
    /* Enable Peripheral clock */
    RCC_APB2PeriphClock_Enable( RCC_APB2PERIPH_GPIOA |
                                //RCC_APB2PERIPH_GPIOB |
                                //RCC_APB2PERIPH_GPIOC |
                                RCC_APB2PERIPH_AF , ENABLE);
    RCC_APB2PeriphClock_Enable(RCC_APB2PERIPH_SPI1,ENABLE); /* Enable clock for SPI1. */
}

void GPIO_Configuration(void)
{
    GPIO_InitPara GPIO_InitStructure;

    /* Configure SPI1 pins: SCK, MISO and MOSI ---------------------------------*/
    /* Confugure SCK and MOSI pins as Alternate Function Push Pull */
    GPIO_InitStructure.GPIO_Pin = GPIO_PIN_5 | GPIO_PIN_7 ;
    GPIO_InitStructure.GPIO_Speed = GPIO_SPEED_50MHZ;
    GPIO_InitStructure.GPIO_Mode = GPIO_MODE_AF_PP;
    GPIO_Init(GPIOA, &GPIO_InitStructure);
    /* Confugure MISO pin as Input Floating  */
    GPIO_InitStructure.GPIO_Pin = GPIO_PIN_6;
    GPIO_InitStructure.GPIO_Mode = GPIO_MODE_IN_FLOATING;
    GPIO_Init(GPIOA, &GPIO_InitStructure);
}

void SPI1_Configuration(void)
{
    SPI_InitPara  SPI_InitStructure;

    /* SPI1 configuration */
    SPI_InitStructure.SPI_TransType = SPI_TRANSTYPE_FULLDUPLEX ;
    SPI_InitStructure.SPI_Mode = SPI_MODE_MASTER;
    SPI_InitStructure.SPI_FrameFormat = SPI_FRAMEFORMAT_8BIT ;
    SPI_InitStructure.SPI_SCKPL = SPI_SCKPL_LOW;    /* POL = */
    SPI_InitStructure.SPI_SCKPH = SPI_SCKPH_1EDGE;  /* PHA =  */
    SPI_InitStructure.SPI_SWNSSEN = SPI_SWNSS_SOFT; /* Software CS. */
    SPI_InitStructure.SPI_PSC = SPI_PSC_16;
    SPI_InitStructure.SPI_FirstBit = SPI_FIRSTBIT_MSB;
    SPI_InitStructure.SPI_CRCPOL = 7;
    SPI_Init(SPI1, &SPI_InitStructure);
    SPI_Enable(SPI1, ENABLE);
}

uint8_t SPI1_SwapBytePolling(uint8_t ch)
{
    while (SPI_I2S_GetBitState(SPI1, SPI_FLAG_TBE) == RESET);
    SPI_I2S_SendData(SPI1, ch);
    while (SPI_I2S_GetBitState(SPI1, SPI_FLAG_RBNE) == RESET);
    return SPI_I2S_ReceiveData( SPI1 );
}

/* EOF. */
